package cn.liberals.org.service.impl;

import cn.liberals.basic.exception.BusinessException;
import cn.liberals.basic.utils.BaiduAuditUtils;
import cn.liberals.basic.utils.PageList;
import cn.liberals.basic.utils.ValidateUtil;
import cn.liberals.org.domain.Employee;
import cn.liberals.org.domain.Shop;
import cn.liberals.org.domain.ShopAuditLog;
import cn.liberals.org.mapper.EmployeeMapper;
import cn.liberals.org.mapper.ShopAuditLogMapper;
import cn.liberals.org.mapper.ShopMapper;
import cn.liberals.org.query.ShopQuery;
import cn.liberals.org.service.IEmployeeService;
import cn.liberals.org.service.IShopService;
import cn.liberals.basic.service.impl.BaseServiceImpl;
import cn.liberals.org.vo.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liberals
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    // 注入邮件对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private IEmployeeService employeeService;

    /* 
    * @Title: 店铺入驻方法
    * @Description: TODO
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/1 17:57  
    * @Parameters: 
    * @Return 
    */
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        // 判断必要参数是否为空，这里我们应该要全部参数都判断是否为空，以名称举例
        // 1.判断参数合法性
        if(shop.getName()==null){
            throw new BusinessException("店铺名不能为空，请重新输入！");
        }
        if(shop.getTel()==null){
            throw new BusinessException("电话不能为空，请重新输入！");
        }
        if(shop.getAddress()==null){
            throw new BusinessException("店铺地址不能为空，请重新输入！");
        }
        if(admin.getUsername()==null){
            throw new BusinessException("管理员名字不能为空，请重新输入！");
        }
        if(admin.getPhone()==null){
            throw new BusinessException("管理员电话不能为空，请重新输入！");
        }
        if(admin.getEmail()==null){
            throw new BusinessException("管理员邮箱不能为空，请重新输入！");
        }
        // 判断邮箱和手机号是否真是有效
        boolean validatePhone = ValidateUtil.validatePhone(admin.getPhone());
        boolean validateEmail = ValidateUtil.validateEmail(admin.getEmail());
        if (!validatePhone){
            throw new BusinessException("无效的手机号，请重新输入！");
        }
        if (!validateEmail){
            throw new BusinessException("无效的邮箱号，请重新输入！");
        }
        if(admin.getPassword()==null || admin.getComfirmPassword()==null){
            throw new BusinessException("请输入两次管理员密码！");
        }
        // 1.5 百度智能校验输入数据合法性

        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BusinessException("LOGO输入非法，请重新输入！");
        }

        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BusinessException("店铺名输入非法，请重新输入！");
        }
        if (!BaiduAuditUtils.TextCensor(admin.getUsername())){
            throw new BusinessException("管理员用户名输入非法，请重新输入！");
        }
        // 两次密码是否一致
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次的密码不一致，请重新输入！");
        }
//                // 校验图片合法性
//        if (!BaiduAuditUtils.ImgCensor(shop.getLogo()){
//            throw new BusinessException("LOGO输入非法，请重新输入！");
//        }

        // 查询店铺是否存在，根据店铺名称查询
        Shop loadShopTmp = shopMapper.loadByName(shop.getName());
            if(loadShopTmp != null){
                  throw new BusinessException("店铺已注册，请重新输入！");
            }

            Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());
            if (!boo){
                throw new BusinessException("请输入合法的消息");
            }

            Boolean boo1 = BaiduAuditUtils.TextCensor(shop.getAdmin().getUsername());
            if (!boo1){
                throw new BusinessException("请输入合法的管理员");
            }
            // 判断图片是否符合要求


        // 查询管理员已经注册过，并且还绑定了某个店铺，这种情况我们认为你不符合我们业务要求，抛出异常
        Employee empTmp = employeeMapper.loadByUserName(admin.getUsername());

            if(empTmp != null && empTmp.getShopId() != null){
                throw new BusinessException("该管理员已绑定店铺，请更换其他管理员！");
            }
        // 管理员没注册，那么注册管理员
        if(empTmp == null){
            // 保存admin，一定要保证返回了主键Id
            employeeService.save(admin);
            empTmp = admin;
        }
        // 如果走到这里，那么管理员绝对已经注册过了
        // 将管理员的主键设置到店铺的外键
        shop.setAdminId(empTmp.getId());
        // 保存店铺,一定要返回主键
        shopMapper.save(shop);
        // 将店铺的主键设置到管理员的外键
        empTmp.setShopId(shop.getId());
        // 修改员工数据
        employeeService.update(empTmp);

    }

    /*
    * @Title: pass
    * @Description: 成功
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/3 21:21
    * @Parameters:
    * @Return
    */
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        // 修改状态
        Long shopId = Long.valueOf(shopAuditLog.getShopId());
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(1);
        shopMapper.update(shop);
        // 保存日志
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.save(shopAuditLog);

        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper  = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("3558731871@qq.com");
            helper.setSubject("宠物乐园店铺入驻结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>亲，您的店铺入驻申请信息我平台已审核通过，请点击下方链接激活店铺</h1>"+
                    "店铺激活链接：<a href='http://localhost:8080/shop/activation/"+shopAuditLog.getShopId()+"'>点我激活店铺</a>",true);
            // 4.设置收件人
            helper.setTo("3558731871@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /* 
    * @Title: reject
    * @Description: 驳回
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/3 10:26  
    * @Parameters: 
    * @Return 
    */
    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        // 修改状态
        Long shopId = Long.valueOf(shopAuditLog.getShopId());
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(-1);
        shopMapper.update(shop);
        // 保存日志信息
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.save(shopAuditLog);
        // 发送修改店铺信息邮件给用户
        // 发送复杂邮件的工具类
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("3558731871@qq.com");
            helper.setSubject("宠物乐园店铺入驻结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>亲，您的店铺入驻申请信息我平台已审核，但是因为内容不合规被驳回，请修改店铺信息后，再次申请</h1>"+
                    "店铺信息修改链接：<a href='http://localhost:8081/#/Register?shopId="+shopAuditLog.getShopId()+"'>点我修改店铺信息</a>",true);
            // 5.设置收件人
            helper.setTo("3558731871@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> loadShopEchartsData() {
        // 报表数据
        List<ShopVo> shopVos = shopMapper.loadShopEchartsData();
        // 把x，y分离出来，因为是两个数组
        // 放到list集合二中
       List<Integer> x1 = shopVos.stream().map(ShopVo::getState).collect(Collectors.toList());
        ArrayList<String> x = new ArrayList<>();
        // 开始转化
        for (int i = 0 ; i < x1.size(); i++){
            if(x1.get(i) == 0){
                x.add(i,"待审核");
            }
            if(x1.get(i) == 1){
                x.add(i,"审核通过");
            }
            if(x1.get(i) == -1){
                x.add(i,"驳回");
            }
            if(x1.get(i) == 2){
                x.add(i,"待激活");
            }
            if(x1.get(i) == 3){
                x.add(i,"拒绝");
            }
        }
        List<Integer> y = shopVos.stream().map(ShopVo::getCountNum).collect(Collectors.toList());
       // 创建map，放入两组数据
        Map<String,Object> data = new HashMap<>();
        data.put("x",x);
        data.put("y",y);
        return data;
    }

    @Override
    public void activation(Long id) {
        Shop shop = shopMapper.loadById(id);
        shop.setState(1);
        shopMapper.update(shop);
    }

    @Override
    public void js(ShopAuditLog shopAuditLog) {
        // 修改状态
        Long shopId = Long.valueOf(shopAuditLog.getShopId());
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(3);
        // 保存日志信息
        shopMapper.update(shop);
        shopAuditLog.setAuditId(325);
        shopAuditLogMapper.save(shopAuditLog);
        // 发送修改店铺信息邮件给用户
        // 发送复杂邮件的工具类
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("3558731871@qq.com");
            helper.setSubject("宠物乐园店铺入驻结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("亲，您的店铺入驻申请信息我平台已审核，但是因为内容不合规拒绝");
            // 4.设置收件人
            helper.setTo("3558731871@qq.com");
            // 5.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void batchSave(List<Shop> shops) {
        shopMapper.batchSave(shops);
    }

    @Override
    public void settlementAgain(Shop shop) {
        if(shop.getName()==null){
            throw new BusinessException("店铺名不能为空，请重新输入！");
        }
        if(shop.getTel()==null){
            throw new BusinessException("电话不能为空，请重新输入！");
        }
        if(shop.getAddress()==null){
            throw new BusinessException("店铺地址不能为空，请重新输入！");
        }
        // 百度智能校验输入数据合法性
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BusinessException("店铺名输入非法，请重新输入！");
        }
        // 校验图片合法性
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BusinessException("LOGO输入非法，请重新输入！");
        }

        // 重置状态为待审核，并修改数据
        shop.setState(0);
        shopMapper.update(shop);
    }

    @Override
    public PageList<Shop> queryData(ShopQuery query) {
        List<Shop> shops = shopMapper.queryData(query);
        ArrayList<Shop> shops1 = new ArrayList<>();
        for(Shop s:shops){
            List<ShopAuditLog> shopAuditLogs = shopAuditLogMapper.loadByShopId(s.getId());
           // shopAuditLogs.forEach(System.out::println);
            ArrayList<ShopAuditLog> shopAuditLogs1 = new ArrayList<>();

            for (ShopAuditLog sa:shopAuditLogs){
                Employee employee = employeeMapper.loadById(Long.valueOf(sa.getAuditId()));
                sa.setAdmin(employee);
                shopAuditLogs1.add(sa);
            }
            s.setAuditLogs(shopAuditLogs1);
            shops1.add(s);
        }

        PageList<Shop> objectPageList = new PageList<>();
        Integer totals = shopMapper.queryCount(query);
        objectPageList.setTotal(totals);
        objectPageList.setRows(shops1);
        return objectPageList;
    }



}
